package conf

import (
	"context"
	"fmt"
	"sync"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type mongoDB struct {
	Endpoints string `toml:"endpoints" json:"endpoints" yaml:"endpoints" env:"ENDPOINTS" envSeparator:","`
	// UserName  string   `toml:"username" json:"username" yaml:"username"  env:"USERNAME"`
	// Password  string   `toml:"password" json:"password" yaml:"password"  env:"PASSWORD"`
	Database string `toml:"database" json:"database" yaml:"database"  env:"DATABASE"`
	// AuthDB    string   `toml:"auth_db" json:"auth_db" yaml:"auth_db"  env:"AUTH_DB"`

	client *mongo.Client

	lock sync.Mutex
}

func (m *mongoDB) uri() string {
	return fmt.Sprintf("mongodb://%s", m.Endpoints)
}

func (m *mongoDB) GetDB() *mongo.Database {
	return m.Client().Database(m.Database)
}

func (m *mongoDB) Client() *mongo.Client {
	m.lock.Lock()
	defer m.lock.Unlock()

	if m.client == nil {
		clientOptions := options.Client().ApplyURI(m.uri())
		client, err := mongo.Connect(context.TODO(), clientOptions)
		if err != nil {
			panic(err)
		}
		if err := client.Ping(context.TODO(), nil); err != nil {
			panic(err)
		}

		m.client = client
	}

	return m.client
}

func MongoDB() *mongoDB {
	return &mongoDB{
		Endpoints: "172.16.1.15:27017",
		Database:  "arm",
	}
}

func (m *mongoDB) Disconnect() error {
	return m.client.Disconnect(context.TODO())
}
